package com.chinaoct.siku.controller;

import com.chinaoct.siku.application.BimApplication;
import com.chinaoct.siku.application.TokenInfoApplication;
import com.chinaoct.siku.util.ResponseMsg;
import com.chinaoct.siku.vo.TokenInfo;
import com.chinaoct.siku.vo.TokenInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {
    @Autowired
    private TokenInfoApplication tokenInfoApplication;

    @Autowired
    private BimApplication bimApplication;



    @RequestMapping("/createToken")
    public ResponseMsg createTokenByBim(String code,String idpIP){
        try {
            Map<String, String> map = bimApplication.loginByBimOauth(code);
            if(null==map || StringUtils.isEmpty(map.get("username"))){
                throw new ServiceException("当前用户无权限，请联系管理员");
            }
            TokenInfo tokenInfo=tokenInfoApplication.createTokenByBim(map.get("username"));
            TokenInfoVO vo= new TokenInfoVO(tokenInfo);
            vo.setName(map.get("name"));
            vo.setUsername(map.get("username"));
            return new ResponseMsg(vo);
        } catch (Exception e) {
          log.error(e.getMessage(),e);
        }
        return  ResponseMsg.error("-1","单点登录失败");
    }



    @RequestMapping("/destroyToken")
    public ResponseMsg destroyToken(HttpServletRequest request){
         String token = request.getHeader("token");
        tokenInfoApplication.destroyToken(token);
         return new ResponseMsg();
    }


}
